package com.sxfq.loansupermarket.backsystem.modular.marketing.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.constant.tips.Tip;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.Role;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.CommUtils;
import com.sxfq.loansupermarket.backsystem.core.util.DateUtil;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.CustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.ICustomerService;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.PayServiceInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.ReservationsInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.SearchReservationsInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.TongJiInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.service.IReservationsService;
import com.sxfq.loansupermarket.backsystem.modular.system.transfer.UserDto;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.AddVisitedInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.service.IConsultantService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 预约客户信息
 *
 * @author py
 * @Date 2018年4月19日23:15:54
 */
@Controller
@RequestMapping("/reservations")
public class ReservationsController extends BaseController {

    @Autowired
    IReservationsService reservationsService;

    @Autowired
    ICustomerService customerService;

    @Autowired
    IConsultantService service;

    @Autowired
    private SqlMapper sqlMapper;

    private String PREFIX = "/marketing/reservations/";

    /**
     * 跳转到预约客户管理页面
     */
    @RequestMapping("")
    public String reservations(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "/reservations.html";
    }

    /**
     * 跳转到市场预约  建档
     */
    @RequestMapping("/reservationsRecord")
    public String reservationsRecord(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "/reservationsRecord.html";
    }

    @RequestMapping(value = "/to_addVisited/{reservationsId}")
    public String toAddVisited(@PathVariable String reservationsId, Model model) {
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("reservationsId", reservationsId);
        return PREFIX + "addVisited.html";
    }

    @RequestMapping(value = "/to_revisitOperation/{reservationsId}")
    public String toRevisitOperation(@PathVariable String reservationsId, Model model) throws Exception {
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        List<AddVisitedInfo> revisitRecordList = service.getRevisitRecordList(reservationsId);
        String sql = "select * from reservations_info where id='" + reservationsId + "' limit 0,1";
        model.addAttribute("reservationsId", reservationsId);
        model.addAttribute("revisitRecordList", revisitRecordList);
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(sql, ReservationsInfo.class);
        if (reservationsInfo != null) {
            if (reservationsInfo.getCustomerSex() != null) {
                if (reservationsInfo.getCustomerSex() == 1) {
                    reservationsInfo.setSex("男");
                }  else if (reservationsInfo.getCustomerSex() == 2) {
                    reservationsInfo.setSex("女");
                }else{  reservationsInfo.setSex("未知");}
            }
        }
        model.addAttribute("reservationsInfo", reservationsInfo);
        model.addAttribute("reservations", ShiroKit.getUser().getAccount());
        return PREFIX + "is_revisit.html";
    }

    @RequestMapping(value = "/addVisited")
    @ResponseBody
    public int addVisited(@Valid CustomerInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql = "update reservations_info set is_return_visit=3,appointment_time=null where id='" + info.getReservationsId() + "'";
        sqlMapper.update(sql);
        return service.insertReturnVisit(info);
    }

    /**
     * 修改到店客户
     */
    @RequestMapping(value = "/add_isRevisit")
    @ResponseBody
    public int addIsRevisit(@Valid CustomerInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String appointmentTime = "";
        if (info.getAppointmentTime() == null || info.getAppointmentTime() == "") {
            appointmentTime = "null";
        } else {
            appointmentTime = "'" + info.getAppointmentTime() + "'";
        }
//            service.updateIsReturnVisit(info);
        service.insertReturnVisit(info);
        String sqlselecthf = "select * from reservations_info a  where a.id='" + info.getReservationsId() + "' limit 0,1";
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(sqlselecthf, ReservationsInfo.class);
        if (reservationsInfo != null) {
            if (reservationsInfo.getHuifang() == null || reservationsInfo.getHuifang() == "") {
                String updatesql = "update reservations_info a set a.statuss='" + info.getStatuss() + "', a.huifang=CONCAT(concat(char(10),' ,<b>" + DateTimeKit.now() + "</b>[" + ShiroKit.getUser().getAccount() + "]:" + info.getRevisitContent() + "'))  where id='" + info.getReservationsId() + "'";
                sqlMapper.update(updatesql);
            } else {
                String updatesql = "update reservations_info a set a.statuss='" + info.getStatuss() + "', a.huifang=CONCAT(huifang,concat(char(10),' ,<b>" + DateTimeKit.now() + "</b>[" + ShiroKit.getUser().getAccount() + "]:" + info.getRevisitContent() + "'))  where id='" + info.getReservationsId() + "'";
                sqlMapper.update(updatesql);
            }
        }
        if (info.getFollower() == null || info.getFollower() == "") {
            String sql = "update reservations_info set  " +
                    "reservations='" + info.getReservations() + "' ,appointment_time=" + appointmentTime + ",return_to_remark='" + ShiroKit.getUser().getAccount() + "'" +
                    " where id='" + info.getReservationsId() + "'";
            return sqlMapper.update(sql);
        } else {
            String sql = "update reservations_info set  " +
                    "reservations='" + info.getReservations() + "',follower='" + info.getFollower() + "',appointment_time=" + appointmentTime + ",return_to_remark='" + ShiroKit.getUser().getAccount() + "'" +
                    " where id='" + info.getReservationsId() + "'";
            return sqlMapper.update(sql);
        }
    }

    @RequestMapping(value = "/openNoRevisit/{reservationsId}")
    public String openNoRevisit(@PathVariable String reservationsId, Model model) {
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        ReservationsInfo reservationsInfo = this.reservationsService.selectOneById(reservationsId);
        model.addAttribute("reservationsInfo", reservationsInfo);
        return PREFIX + "openNoRevisit.html";
    }

    @RequestMapping(value = "/openRevisit/{reservationsId}")
    public String openRevisit(@PathVariable String reservationsId, Model model) {
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        ReservationsInfo reservationsInfo = this.reservationsService.selectOneById(reservationsId);
        model.addAttribute("reservationsInfo", reservationsInfo);
        return PREFIX + "openRevisit.html";
    }

    /**
     * 跳转到预约客户管理添加页面
     */
    @RequestMapping(value = "/reservations_add")
    public String reservationsAdd(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "reservations_add.html";
    }

    @RequestMapping(value = "/to_archiving")
    public String to_archiving(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "archiving.html";
    }

    @RequestMapping(value = "/to_follower")
    public String to_follower(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "follower.html";
    }

    @RequestMapping(value = "/to_belonger")
    public String to_belonger(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "belonger.html";
    }

    /**
     * 跳转到预约客户管理详情页面
     */
    @RequestMapping(value = "/reservations_update/{reservationsId}")
    public String reservationsUpdate(@PathVariable String reservationsId, Model model) {
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        ReservationsInfo reservationsInfo = this.reservationsService.selectOneById(reservationsId);
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("reservationsInfo", reservationsInfo);
        return PREFIX + "reservations_edit.html";
    }

    @RequestMapping(value = "/reservations_AdministratorsUpdate/{reservationsId}")
    public String reservationsAdministratorsUpdate(@PathVariable String reservationsId, Model model) {
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        ReservationsInfo reservationsInfo = this.reservationsService.selectOneById(reservationsId);
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("reservationsInfo", reservationsInfo);
        return PREFIX + "administrators_update.html";
    }

    @RequestMapping(value = "/to_internetAdministratorsUpdate/{reservationsId}")
    public String toInternetAdministratorsUpdate(@PathVariable String reservationsId, Model model) {
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        ReservationsInfo reservationsInfo = this.reservationsService.selectOneById(reservationsId);
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("reservationsInfo", reservationsInfo);
        return PREFIX + "internett_administrators_update.html";
    }

    /**
     * 跳转到预约客户管理详情页面
     */
    @RequestMapping(value = "/reservations_supplement/{customerPhone}")
    public String reservationsSupplementUpdate(@PathVariable String customerPhone, Model model) {
        if (ToolUtil.isEmpty(customerPhone)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        List<ReservationsInfo> reservationsInfoList = this.reservationsService.selectOneByPhone(customerPhone);
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("reservationsInfoList", reservationsInfoList);
        return PREFIX + "reservations_supplement_list.html";
    }

    @RequestMapping(value = "/to_addChatRecord/{id}")
    public String to_addChatRecord(@PathVariable String id, Model model) {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select * from reservations_info where id='" + id + "' limit 0,1";
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(sql, ReservationsInfo.class);
        model.addAttribute("id", id);
        model.addAttribute("reservationsInfo", reservationsInfo);
        return PREFIX + "add_chat_record.html";
    }

    @RequestMapping(value = "/reservationsSupplement/{reservationsId}")
    public String reservationsSupplement(@PathVariable String reservationsId, Model model) {
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        ReservationsInfo reservationsInfo = this.reservationsService.selectOneById(reservationsId);
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("reservationsInfo", reservationsInfo);
        return PREFIX + "reservations_supplement_edit.html";
    }

    @RequestMapping(value = "/reservations_details/{reservationsId}")
    public String reservationsDetails(@PathVariable String reservationsId, Model model) {
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        ReservationsInfo reservationsInfo = this.reservationsService.selectOneById(reservationsId);
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("reservationsInfo", reservationsInfo);
        return PREFIX + "reservationCustomer_edit.html";
    }

    @RequestMapping(value = "/getTotleMoney", method = RequestMethod.POST)
    @ResponseBody
    public Double getTotleMoney(String id) throws Exception {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql = "select table_name from information_schema.tables where table_schema='crms'\n" +
                "and table_name like  '%customer_info%'";
        List<ReservationsInfo> list = sqlMapper.selectList(sql, ReservationsInfo.class);
        String sql2 = "";
        Double actualAccountBalance = 0.00;
        for (int i = 0; i < list.size(); i++) {
            sql2 = "select actual_account_balance as actualAccountBalance " +
                    "from " + list.get(i).getTableName() + " t where t.reservations_id='" + id + "' limit 0,1";
            PayServiceInfo info = sqlMapper.selectOne(sql2, PayServiceInfo.class);
            if (info != null) {
                actualAccountBalance += info.getActualAccountBalance();
            }
        }
        return actualAccountBalance;
    }

    @RequestMapping(value = "/getHuiFang", method = RequestMethod.POST)
    @ResponseBody
    public String getHuiFang(String id) throws Exception {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql = "select id as id,huifang as huifang from reservations_info where id='" + id + "' limit 0,1";
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(sql, ReservationsInfo.class);
        String huifang = "";
        if (reservationsInfo != null) {
            huifang = reservationsInfo.getHuifang();
        }
        return huifang;
    }

    @RequestMapping(value = "/getTotleMoneys", method = RequestMethod.POST)
    @ResponseBody
    public Double getTotleMoneys(String id) throws Exception {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "customer_info";
        Double actualAccountBalance = 0.00;
        String sql2 = "select actual_account_balance as actualAccountBalance " +
                "from " + tableName + " t where t.reservations_id='" + id + "' limit 0,1";
        PayServiceInfo info = sqlMapper.selectOne(sql2, PayServiceInfo.class);
        if (info != null) {
            actualAccountBalance += info.getActualAccountBalance();
        }
        return actualAccountBalance;
    }

    @RequestMapping(value = "/getArchiving", method = RequestMethod.GET)
    @ResponseBody
    public List<UserDto> getArchiving() throws Exception {
        String selectsql = "select * from role a where  a.name='市场' limit 0,1";
        Role role = sqlMapper.selectOne(selectsql, Role.class);
        String sql = "select t.id,t.account from user t where t.roleid like CONCAT('%','" + role.getId() + "','%') ";
        List<UserDto> list = sqlMapper.selectList(sql, UserDto.class);
        return list;
    }

    @RequestMapping(value = "/funs", method = RequestMethod.GET)
    @ResponseBody
    public Model funs(Model model) {
        String sql = "select * from " + this.getTableName() + "";
        List<CustomerInfo> getList = sqlMapper.selectList(sql, CustomerInfo.class);
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("getList", getList);
        return model;
    }

    @RequestMapping(value = "/to_revisitRecord/{reservationsId}")
    public String appointment(Model model, @PathVariable String reservationsId) throws Exception {
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        List<AddVisitedInfo> revisitRecordList = service.getRevisitRecordList(reservationsId);
        String sql = "select * from reservations_info where id='" + reservationsId + "'";
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(sql, ReservationsInfo.class);
        model.addAttribute("reservationsId", reservationsId);
        if (reservationsInfo != null) {
            if (reservationsInfo.getCustomerSex() != null) {
                if (reservationsInfo.getCustomerSex() == 1) {
                    reservationsInfo.setSex("男");
                }  else if (reservationsInfo.getCustomerSex() == 2) {
                    reservationsInfo.setSex("女");
                }else{  reservationsInfo.setSex("未知");}
            }
        }
        model.addAttribute("reservationsInfo", reservationsInfo);
        model.addAttribute("reservationsId", reservationsId);
        model.addAttribute("revisitRecordList", revisitRecordList);
        return PREFIX + "revisitRecord.html";
    }

    /**
     * 预约客户管理列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object testrInfoList(SearchReservationsInfo info, HttpServletRequest request) {
        Page<ReservationsInfo> page = new PageFactory<ReservationsInfo>().defaultPage();
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return REDIRECT + "/login";
        }
        try {
            List<ReservationsInfo> list = new ArrayList<ReservationsInfo>();
            list = reservationsService.selectPageListByQueryGetMap(page, info);
            if (list.size() == 0) {
                page.setCurrent(1);
                list = reservationsService.selectPageListByQueryGetMap(page, info);
            }
            page.setRecords(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }


    /**
     * 添加预约客户
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public int add(@Valid ReservationsInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String phone = info.getCustomerPhone();
        //查询已有手机号的预约集合
        List<ReservationsInfo> existList = reservationsService.getCustomerPhoneCounts(info.getCustomerPhone());
        int count = existList.size();
        if (!"本人".equals(info.getPhoneSharShip())) {
            info.setCustomerPhone(info.getCustomerPhone() + "+" + count);
        } else {
            if (reservationsService.getCustomerPhoneCount(info).size() > 0) {
                return 0;
            } else {
                //获取最近的第一个手机号，如果超过一年就返回0 失败
                if (existList.size() > 0) {
                    ReservationsInfo lastInfo = existList.get(0);
                    //建档日期字符串转换成日期格式
                    Date fileTimeData = DateUtil.parse(lastInfo.getFilingTime(), "yyyy-MM-dd HH:mm:ss");
                    //当期时间
                    Date currentDate = new Date();
                    //date.getTime()方法是获取时间戳，当前时间戳-建档时间戳就是表示两个时间之间的差值（毫秒）
                    if (currentDate.getTime() - fileTimeData.getTime() < 365 * 24 * 60 * 60 * 1000) {
                        return 0;
                    }
                }
                info.setCustomerPhone(phone);
                reservationsService.insert(info);
                return 1;
            }
        }
        reservationsService.insert(info);
        return 1;
    }
//    /**
//     * 添加预约客户补单
//     */
//    @RequestMapping(value = "/supplement")
//    @ResponseBody
//    public int supplement(@Valid ReservationsInfo info, BindingResult result) throws Exception {
//        if (result.hasErrors()) {
//            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
//        }
//        String phone = info.getCustomerPhone();
//        int count = reservationsService.getCustomerPhoneCounts(info.getCustomerPhone()).size();
//        if (!"本人".equals(info.getPhoneSharShip())) {
//            info.setCustomerPhone(info.getCustomerPhone() + "+" + count);
//        }
//        if (reservationsService.getCustomerPhoneCount(info).size() > 0) {
//            return 0;
//        } else {
//            info.setCustomerPhone(phone);
//            reservationsService.supplement(info);
//            return 1;
//        }
//    }

    /**
     * 删除预约客户
     */
    @RequestMapping(value = "/delete/{id}")
    @ResponseBody
    public Tip delete(@PathVariable String id) throws Exception {
        ReservationsInfo reservations = reservationsService.selectOneById(id);
        reservationsService.insertDelete(reservations);
        reservationsService.delete(id);
        return SUCCESS_TIP;
    }

    /**
     * 删除预约客户
     */
    @RequestMapping(value = "/deletes")
    @ResponseBody
    public Tip deletes(@Valid String id) throws Exception {
        ReservationsInfo reservations = reservationsService.selectOneById(id);
        reservationsService.insertDelete(reservations);
        reservationsService.delete(id);
        return SUCCESS_TIP;
    }

    /**
     * 跳转到添加回访
     */
    @RequestMapping(value = "/reservations_addReturn/{id}")
    public String reservations_addReturn(Model model, @PathVariable String id) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("id", id);
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "reservations_addReturn.html";
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/update/{cri}")
    @ResponseBody
    public int update(@Valid ReservationsInfo info, BindingResult result, @PathVariable String cri) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String phone2=cri.split(",")[0];
        String belonger=cri.split(",")[1];
        if("没人".equals(belonger)||belonger=="没人"){
            info.setBelonger("");
        }else {
            info.setBelonger(belonger);
        }
        String phone = info.getCustomerPhone();
        if (phone2 != null && !"phone2".equals(phone2)) {
            phone = info.getCustomerPhone() + "," + phone2;
        }
        int count = reservationsService.getCustomerPhoneCounts(info.getCustomerPhone()).size();
        if (!"本人".equals(info.getPhoneSharShip())) {
            info.setCustomerPhone(info.getCustomerPhone() + "+" + count);
        }
        if (reservationsService.getUpdatePhoneCount(info) > 0) {
            return 0;
        } else {
            info.setCustomerPhone(phone);
            reservationsService.update(info);
            return 1;
        }
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/adminUpdate")
    @ResponseBody
    public int adminUpdate(@Valid ReservationsInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String phone = info.getCustomerPhone();
        int count = reservationsService.getCustomerPhoneCounts(info.getCustomerPhone()).size();
        if (!"本人".equals(info.getPhoneSharShip())) {
            info.setCustomerPhone(info.getCustomerPhone() + "+" + count);
        }
        if (reservationsService.getUpdatePhoneCount(info) > 0) {
            return 0;
        } else {
            info.setCustomerPhone(phone);
//            reservationsService.update(info);
            reservationsService.adminUpdate(info);
            reservationsService.reservationsUpdate(info);
            return 1;
        }
    }

    @RequestMapping(value = "/addChatRecord")
    @ResponseBody
    public int addChatRecord(@Valid ReservationsInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String updatesql = "update reservations_info a set a.content='" + info.getContent() + "' where id='" + info.getId() + "'";
        sqlMapper.update(updatesql);
        return 1;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/supplement_update")
    @ResponseBody
    public int supplement_update(@Valid ReservationsInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String phone = info.getCustomerPhone();
        int count = reservationsService.getCustomerPhoneCounts(info.getCustomerPhone()).size();
        if (!"本人".equals(info.getPhoneSharShip())) {
            info.setCustomerPhone(info.getCustomerPhone() + "+" + count);
        }
        if (reservationsService.getUpdatePhoneCount(info) > 0) {
            return 0;
        } else {
            String sql = "INSERT INTO `supplement_log` ( `logtype` ,`customer_name`,`customer_phone`, `single_person`,`userid`, `classname`, `method`, `createtime`, `succeed`, `message`) VALUES\n" +
                    " ( '补单','" + info.getCustomerName() + "','" + info.getCustomerPhone() + "','" + ShiroKit.getUser().getAccount() + "', " + ShiroKit.getUser().getId() + ", '" + ShiroKit.getUser().getAccount() + "补单 电话：" + phone + " 姓名：" + info.getCustomerName() + " id:" + info.getId() + "', 'supplement', '" + DateTimeKit.now() + "', '成功', '" + ShiroKit.getUser().getAccount() + "');";
            sqlMapper.insert(sql);
            info.setCustomerPhone(phone);
            reservationsService.supplementUpdate(info);
            return 1;
        }
    }

    public String getTableName() {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "customer_info";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return tableName;
    }

    @RequestMapping(value = "/customer_import")
    public String to_import(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return PREFIX + "customer_import.html";
    }

    /**
     * 导入
     */
    @RequestMapping(value = "/upload")
    public String importTestQuestions(@Valid MultipartFile file) {
        if (!StringUtil.isEmpty(file)) {
            Random random = new Random();
            String realPath = "D:\\yiyatmp\\" + random.nextInt(100);
            String FileInput = realPath + "\\" + file.getOriginalFilename();
            try {
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, file.getOriginalFilename()));
                InputStream is = new FileInputStream(FileInput);
                HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
                // 循环工作表Sheet
                Sheet hssfSheet = hssfWorkbook.getSheetAt(0);
                Row hssfRow0 = hssfSheet.getRow(0);
                for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                    Row hssfRow = hssfSheet.getRow(rowNum);
                    if (hssfRow == null) {
                        continue;
                    }
                    Cell xh1 = hssfRow.getCell(0);
                    Cell xh2 = hssfRow.getCell(1);
                    Cell xh3 = hssfRow.getCell(2);
                    Cell xh4 = hssfRow.getCell(3);
                    Cell xh5 = hssfRow.getCell(4);
                    Cell xh6 = hssfRow.getCell(5);
                    Cell xh7 = hssfRow.getCell(6);
                    Cell xh8 = hssfRow.getCell(7);
                    Cell xh9 = hssfRow.getCell(8);
                    Cell xh10 = hssfRow.getCell(9);
                    Cell xh11 = hssfRow.getCell(10);
                    Cell xh12 = hssfRow.getCell(11);
                    Cell xh13 = hssfRow.getCell(12);
                    Cell xh14 = hssfRow.getCell(13);
                    Cell xh15 = hssfRow.getCell(14);
                    Cell xh16 = hssfRow.getCell(15);
                    Cell xh17 = hssfRow.getCell(16);
                    Cell xh18 = hssfRow.getCell(17);
                    Cell xh19 = hssfRow.getCell(18);
                    Cell xh20 = hssfRow.getCell(19);
                    Cell xh21 = hssfRow.getCell(20);
                    Cell xh22 = hssfRow.getCell(21);
                    Cell xh23 = hssfRow.getCell(22);
                    Cell xh24 = hssfRow.getCell(23);
                    String xh1s = "";
                    String xh2s = "";
                    String xh3s = "";
                    String xh4s = "";
                    String xh5s = "";
                    String xh6s = "";
                    String xh7s = "";
                    String xh8s = "";
                    String xh9s = "";
                    String xh10s = "";
                    String xh11s = "";
                    String xh12s = "";
                    String xh13s = "";
                    String xh14s = "";
                    String xh15s = "";
                    String xh16s = "";
                    String xh17s = "";
                    String xh18s = "";
                    String xh19s = "";
                    String xh20s = "";
                    String xh21s = "";
                    String xh22s = "";
                    String xh23s = "";
                    String xh24s = "";
                    String xh25s = "";
                    if ((xh1 + "") == null || ("").equals((xh1 + ""))) {
                        xh1s = "null";
                    } else {
                        xh1s = "'" + xh1 + "'";
                    }
                    if ((xh2 + "") == null || ("").equals((xh2 + ""))) {
                        xh2s = "null";
                    } else {
                        xh2s = "'" + xh2 + "'";
                    }
                    if ((xh3 + "") == null || ("").equals((xh3 + ""))) {
                        xh3s = "null";
                    } else {
                        xh3s = "'" + xh3 + "'";
                    }
                    if ((xh4 + "") == null || ("").equals((xh4 + ""))) {
                        xh4s = "null";
                    } else {
                        xh4s = "'" + xh4 + "'";
                    }
                    if (xh5.toString() != null) {
                        xh5s = xh5.toString();
                    } else {
                        xh5s = null;
                    }
                    if ((xh6 + "") == null || ("").equals((xh6 + ""))) {
                        xh6s = "null";
                    } else {
                        xh6s = "'" + xh6 + "'";
                    }
                    if ((xh7 + "") == null || ("").equals((xh7 + ""))) {
                        xh7s = "null";
                    } else {
                        xh7s = "'" + xh7 + "'";
                    }
                    if ((xh8 + "") == null || ("").equals((xh8 + ""))) {
                        xh8s = "null";
                    } else {
                        xh8s = "'" + xh8 + "'";
                    }
                    if ((xh9 + "") == null || ("").equals((xh9 + ""))) {
                        xh9s = "null";
                    } else {
                        xh9s = "'" + xh9 + "'";
                    }
                    if ((xh10 + "") == null || ("").equals((xh10 + ""))) {
                        xh10s = "null";
                    } else {
                        xh10s = "'" + xh10 + "'";
                    }
                    if ((xh11 + "") == null || ("").equals((xh11 + ""))) {
                        xh11s = "null";
                    } else {
                        xh11s = "'" + xh11 + "'";
                    }
                    if ((xh12 + "") == null || ("").equals((xh12 + ""))) {
                        xh12s = "null";
                    } else {
                        xh12s = "'" + xh12 + "'";
                    }
                    if ((xh13 + "") == null || ("").equals((xh13 + ""))) {
                        xh13s = "null";
                    } else {
                        xh13s = "'" + xh13 + "'";
                    }
                    if ((xh14 + "") == null || ("").equals((xh14 + ""))) {
                        xh14s = "null";
                    } else {
                        xh14s = "'" + xh14 + "'";
                    }
                    if ((xh15 + "") == null || ("").equals((xh15 + ""))) {
                        xh15s = "null";
                    } else {
                        xh15s = "'" + xh15 + "'";
                    }
                    if ((xh16 + "") == null || ("").equals((xh16 + ""))) {
                        xh16s = "null";
                    } else {
                        xh16s = "'" + xh16 + "'";
                    }
                    if ((xh17 + "") == null || ("").equals((xh17 + ""))) {
                        xh17s = "null";
                    } else {
                        xh17s = "'" + xh17 + "'";
                    }
                    if ((xh18 + "") == null || ("").equals((xh18 + ""))) {
                        xh18s = "null";
                    } else {
                        xh18s = "'" + xh18 + "'";
                    }
                    if ((xh19 + "") == null || ("").equals((xh19 + ""))) {
                        xh19s = "null";
                    } else {
                        xh19s = "'" + xh19 + "'";
                    }
                    if ((xh20 + "") == null || ("").equals((xh20 + ""))) {
                        xh20s = "null";
                    } else {
                        xh20s = "'" + xh20 + "'";
                    }
                    if ((xh21 + "") == null || ("").equals((xh21 + ""))) {
                        xh21s = "null";
                    } else {
                        xh21s = "'" + xh21 + "'";
                    }
                    if ((xh22 + "") == null || ("").equals((xh22 + ""))) {
                        xh22s = "null";
                    } else {
                        xh22s = "'" + xh22 + "'";
                    }
                    if ((xh23 + "") == null || ("").equals((xh23 + ""))) {
                        xh23s = "null";
                    } else {
                        xh23s = "'" + xh23 + "'";
                    }
                    if ((xh24 + "") == null || ("").equals((xh24 + ""))) {
                        xh24s = "null";
                    } else {
                        xh24s = "'" + xh24 + "'";
                    }
                    String ageRange = "";
                    if (xh5s != null) {
                        for (int i = 0; i < 11; i++) {
                            if (Integer.parseInt(xh5s) >= (i * 10) && Integer.parseInt(xh5s) <= (i * 10 + 9)) {
                                ageRange = (i * 10) + "-" + (i * 10 + 9);
                            }
                        }
                    }

                    String id = CommUtils.getUUID();
                    Random rand = new Random();
                    int randomNumber = rand.nextInt(999999);
                    id = id + randomNumber;

                    String sql = "insert into  reservations_info " +
                            "(id,customer_name,customer_phone,customer_sex,customer_age,wechat_number,appointment_pay_service,content,medium,channel,engine_key," +
                            "remarks,archiving ,appointment_time ,filing_time,jiedai_content ,money ,department, huifang ,reservations_num ,expenditure_project ," +
                            "status ,statuss ,doctor, age_range,outpatient_name) VALUES " +
                            "('" + id + "' , " + xh2s + " , " + xh3s + " " +
                            ", " + xh4s + " , " + xh5s + " , " + xh6s + " " +
                            ", " + xh7s + " , " + xh8s + " , " + xh9s + " , " + xh10s + " , " + xh11s + " ," +
                            " " + xh12s + " , " + xh13s + " , " + xh14s + " , " + xh15s + " , " + xh16s + " ," +
                            " " + xh17s + " , " + xh18s + " , " + xh19s + "," + xh20s + "," + xh21s + "" +
                            "," + xh22s + "," + xh23s + "," + xh24s + ",'" + ageRange + "','德米店' );";
//                    String sql = " update reservations_info set access_disease='" + xh3 + "'  where customer_phone='" + xh2 + "'" +
//                            " and customer_name='" + xh1 + "'";
//                    String sql = " update reservations_info set status='" + xh3 + "'  where customer_phone='" + xh2 + "'" +
//                            " and customer_name='" + xh1 + "'  ";
                    sqlMapper.insert(sql);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return PREFIX + "testClose.html";
        } else {
            return PREFIX + "testClose.html";
        }
    }

    @RequestMapping(value = "/reservationsExport")
    public void reservationsExport(@RequestParam(required = false) String customerName, @RequestParam(required = false) String status,
                                   @RequestParam(required = false) String customerPhone, @RequestParam(required = false) String appointmentPayService,
                                   @RequestParam(required = false) String startRevisitTime, @RequestParam(required = false) String endRevisitTime,
                                   @RequestParam(required = false) String archiving, @RequestParam(required = false) String accessDisease,
                                   @RequestParam(required = false) String startFilingTime, @RequestParam(required = false) String endFilingTime,
                                   @RequestParam(required = false) String outpatientName, @RequestParam(required = false) String startArrivalTime,
                                   @RequestParam(required = false) String endArrivalTime, @RequestParam(required = false) String oneChannel,
                                   @RequestParam(required = false) String twoChannel, @RequestParam(required = false) String isReturnVisit,
                                   @RequestParam(required = false) String thrChannel, @RequestParam(required = false) String reservationsNum,
                                   @RequestParam(required = false) String wechatNumber, @RequestParam(required = false) String statuss,
                                   @RequestParam(required = false) String tcName, @RequestParam(required = false) String department,
                                   HttpServletResponse response) {
        try {
            SearchReservationsInfo searchInfo = new SearchReservationsInfo();
            searchInfo.setCustomerName(customerName);
            searchInfo.setStatus(status);
            searchInfo.setStatuss(statuss);
            searchInfo.setTcName(tcName);
            searchInfo.setCustomerPhone(customerPhone);
            searchInfo.setAppointmentPayService(appointmentPayService);
            searchInfo.setStartRevisitTime(startRevisitTime);
            searchInfo.setArchiving(archiving);
            searchInfo.setAccessDisease(accessDisease);
            searchInfo.setStartFilingTime(startFilingTime);
            searchInfo.setEndFilingTime(endFilingTime);
            searchInfo.setOutpatientName(outpatientName);
            searchInfo.setStartArrivalTime(startArrivalTime);
            searchInfo.setEndArrivalTime(endArrivalTime);
            searchInfo.setOneChannel(oneChannel);
            searchInfo.setTwoChannel(twoChannel);
            searchInfo.setThrChannel(thrChannel);
            searchInfo.setReservationsNum(reservationsNum);
            searchInfo.setIsReturnVisit(Integer.parseInt(isReturnVisit));
            searchInfo.setWechatNumber(wechatNumber);
            searchInfo.setDepartment(department);
            List<ReservationsInfo> list = reservationsService.reservationsExport(searchInfo);
            // 解析成excel文件
            // 第一步，创建一个webbook，对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步，在wb中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("前端导出");
            for (int i = 0; i < 19; i++) {
                sheet.setColumnWidth(i, 24 * 256);
            }
            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow(0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);// 创建一个居中格式
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("姓名");
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue("性别");
            cell.setCellStyle(style);
            cell = row.createCell(2);
            cell.setCellValue("年龄");
            cell.setCellStyle(style);
            cell = row.createCell(3);
            cell.setCellValue("手机号");
            cell.setCellStyle(style);
            cell = row.createCell(4);
            cell.setCellValue("微信号");
            cell.setCellStyle(style);
            cell = row.createCell(5);
            cell.setCellValue("建档人");
            cell.setCellStyle(style);
            cell = row.createCell(6);
            cell.setCellValue("一级渠道");
            cell.setCellStyle(style);
            cell = row.createCell(7);
            cell.setCellValue("二级渠道");
            cell.setCellStyle(style);
            cell = row.createCell(8);
            cell.setCellValue("三级渠道");
            cell.setCellStyle(style);
            cell = row.createCell(9);
            cell.setCellValue("预约门诊");
            cell.setCellStyle(style);
            cell = row.createCell(10);
            cell.setCellValue("到店状态");
            cell.setCellStyle(style);
            cell = row.createCell(11);
            cell.setCellValue("预约病种");
            cell.setCellStyle(style);
            cell = row.createCell(12);
            cell.setCellValue("访问病种");
            cell.setCellStyle(style);
            cell = row.createCell(13);
            cell.setCellValue("建档时间");
            cell.setCellStyle(style);
            cell = row.createCell(14);
            cell.setCellValue("首次到店时间");
            cell.setCellStyle(style);
            cell = row.createCell(15);
            cell.setCellValue("成交状态");
            cell.setCellStyle(style);
            cell = row.createCell(16);
            cell.setCellValue("成交金额");
            cell.setCellStyle(style);
            cell = row.createCell(17);
            cell.setCellValue("初诊tc");
            cell.setCellStyle(style);
            cell = row.createCell(18);
            cell.setCellValue("消费项目");
            cell.setCellStyle(style);
            // 填充数据
            for (int i = 0; i < list.size(); i++) {
                ReservationsInfo map = list.get(i);
                row = sheet.createRow(i + 1);
                customerName = map.getCustomerName();
                String sex = map.getSex();
                int customerAge = 0;
                if (map.getCustomerAge() != null) {
                    customerAge = map.getCustomerAge();
                }
                customerPhone = map.getCustomerPhone();
                wechatNumber = map.getWechatNumber();
                archiving = map.getArchiving();
                oneChannel = map.getOneChannel();
                twoChannel = map.getTwoChannel();
                thrChannel = map.getThrChannel();
                outpatientName = map.getOutpatientName();
                status = map.getStatus();
                tcName = map.getTcName();
                appointmentPayService = map.getAppointmentPayService();
                String filingTime = map.getFilingTime();
                String firstVisitDate = map.getFirstVisitDate();
                String dealStatus = map.getDealStatus();
                String accessDiseases = map.getAccessDisease();
                Double money = map.getMoney();
                if (money == null) {
                    money = 0.00;
                }
                String payServiceName = "";
                if (StringUtil.isNotEmpty(map.getPayServiceName())) {
                    payServiceName = map.getPayServiceName();
                }
                String id = map.getId();
                // 第四步，创建单元格，并设置值
                for (int j = 0; j <= 19; j++) {
                    row.createCell(j).setCellStyle(style);
                }
                row.getCell(0).setCellValue(customerName);
                row.getCell(1).setCellValue(sex);
                row.getCell(2).setCellValue(customerAge);
                row.getCell(3).setCellValue(customerPhone);
                row.getCell(4).setCellValue(wechatNumber);
                row.getCell(5).setCellValue(archiving);
                row.getCell(6).setCellValue(oneChannel);
                row.getCell(7).setCellValue(twoChannel);
                row.getCell(8).setCellValue(thrChannel);
                row.getCell(9).setCellValue(outpatientName);
                row.getCell(10).setCellValue(status);
                row.getCell(11).setCellValue(appointmentPayService);
                row.getCell(12).setCellValue(accessDiseases);
                row.getCell(13).setCellValue(filingTime);
                row.getCell(14).setCellValue(firstVisitDate);
                row.getCell(15).setCellValue(dealStatus);
                row.getCell(16).setCellValue(money);
                row.getCell(17).setCellValue(tcName);
                row.getCell(18).setCellValue(payServiceName);
            }

            String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
            String filename = "data" + date + ".xls";
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}